from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from .models import WasteClassification, UserSubmission


@csrf_exempt
@require_http_methods(["GET"])
def waste_classification_view(request):
    try:
        qs = WasteClassification.objects.all()
        q = request.GET.get('q')
        category = request.GET.get('category')
        city = request.GET.get('city')
        page = int(request.GET.get('page') or 1)
        page_size = int(request.GET.get('page_size') or 10)

        if category:
            allowed = [c[0] for c in WasteClassification.CATEGORY_CHOICES]
            if category not in allowed:
                return JsonResponse({'success': False, 'message': '分类不在可选范围'}, status=400)
            qs = qs.filter(category=category)
        if city:
            allowed = [c[0] for c in WasteClassification.CITY_CHOICES]
            if city not in allowed:
                return JsonResponse({'success': False, 'message': '城市不在可选范围'}, status=400)
            qs = qs.filter(city=city)
        if q:
            qs = qs.filter(Q(item_name__icontains=q) | Q(description__icontains=q))

        total = qs.count()
        start = (page - 1) * page_size
        end = start + page_size
        items = [{
            'waste_id': w.waste_id,
            'item_name': w.item_name,
            'category': w.category,
            'city': w.city,
            'description': w.description,
        } for w in qs.order_by('item_name')[start:end]]

        return JsonResponse({'success': True, 'data': {'items': items, 'meta': {'page': page, 'page_size': page_size, 'total': total}}})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def submissions_view(request):
    try:
        if not request.user.is_authenticated:
            return JsonResponse({'success': False, 'message': '未登录'}, status=401)
        if request.method == 'GET':
            qs = UserSubmission.objects.filter(user=request.user)
            page = int(request.GET.get('page') or 1)
            page_size = int(request.GET.get('page_size') or 10)
            total = qs.count()
            start = (page - 1) * page_size
            end = start + page_size
            items = [{
                'submission_id': s.submission_id,
                'term': s.term,
                'ai_temp_answer': s.ai_temp_answer,
                'status': s.status,
                'created_at': s.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            } for s in qs.order_by('-created_at')[start:end]]
            return JsonResponse({'success': True, 'data': {'items': items, 'meta': {'page': page, 'page_size': page_size, 'total': total}}})

        # POST
        data = request.POST if request.content_type != 'application/json' else __import__('json').loads(request.body or '{}')
        term = (data.get('term') or '').strip()
        ai_temp_answer = (data.get('ai_temp_answer') or '').strip() or None
        if not term:
            return JsonResponse({'success': False, 'message': '词条不能为空'}, status=400)
        s = UserSubmission.objects.create(user=request.user, term=term, ai_temp_answer=ai_temp_answer, status='pending')
        return JsonResponse({'success': True, 'message': '提交成功', 'data': {'submission_id': s.submission_id}}, status=201)
    except __import__('json').JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)
